package com.example.demo.common.utils;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
public class HttpUtil {

    static Logger log = LoggerFactory.getLogger(HttpUtil.class);

    static OkHttpClient okHttpClient = null;

    private static OkHttpClient getOkHttpClient() {
        if (okHttpClient == null) {
            okHttpClient = new OkHttpClient();
        }
        return okHttpClient;
    }


    /**
     * post请求参数
     *
     * @param bodyParams
     * @return
     */
    private static RequestBody setRequestBody(String bodyParams) {
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), bodyParams);
        return body;
    }


    /**
     *
     * @param url
     * @param encryptResult
     * @param appKey
     * @param secretKey
     * @return
     */
    public static String postRequest(String url, String encryptResult, String appKey, String secretKey) {
        String timestamp = String.valueOf(System.currentTimeMillis());
        RequestBody body = setRequestBody(encryptResult);
        String localString = encryptResult + "&Timestamp=" + timestamp + "&AppKey=" + appKey + "&Version=1.0" + "&SecretKey" + secretKey;
        //签名
        String sigin = Md5Util.getMd5(localString);
        Request request = new Request.Builder()
                .addHeader("AppKey", appKey)
                .addHeader("Timestamp", timestamp)
                .addHeader("Version", "1.0")
                .addHeader("Sign", sigin)
                .url(url)
                .post(body)
                .build();
        Call call = getOkHttpClient().newCall(request);
        try {
            Response response = call.execute();
            String res = response.body().string();
            log.info("res====" + res);
            return res;
        } catch (IOException e) {
            log.error("HttpUtil.post网络请求失败：{}", e.getMessage());
            return "网络请求失败";
        }
    }

    public static BaseResponse post(String url,String paramsJson,String appKey,String secretkey,String publicKey){
        String encjson = "";
        try {
            //RSA加密
            encjson = RSAHelper.encryptByPublicKey(paramsJson, publicKey);
        } catch (Exception e) {
            e.printStackTrace();
            return new BaseResponse("publicKey 错误");
        }
        String result = postRequest(url,encjson,appKey,secretkey);
        BaseResponse baseResponse = JSONObject.parseObject(result,BaseResponse.class);
        return baseResponse;
    }

}
